<template>
  <rt-view>
    <rt-form ref="insertForm" :model="insertForm" :rules="rules">
      <rt-header>
        <rt-detail-header :auto-back="false" @back="back">
          <rt-header-icon slot="icon" icon="rt-portal-default" />
          <rt-header-title title="创建活动" />
          <template slot="btn">
            <!-- 保存 -->
            <rt-header-button-group v-if="!isUpdate">
              <rt-button icon-name="rt-portal-export" @click="releaseCampaign()"
                >发布</rt-button
              >
              <rt-button
                icon-name="rt-base-save"
                type="primary"
                @click="saveCampaign()"
                >保存</rt-button
              >
            </rt-header-button-group>
            <!-- 更新 -->
            <rt-header-button-group v-if="isUpdate">
              <rt-button
                v-if="insertForm.bbs_campaign_status == 2"
                icon-name="rt-base-disable"
                @click="deactivateRelease"
                >取消发布</rt-button
              >
              <rt-button
                v-if="insertForm.bbs_campaign_status == 1"
                icon-name="rt-portal-able"
                @click="releaseCampaign()"
                >发布</rt-button
              >
              <rt-button icon-name="rt-base-delete" @click="deleteCampaign()"
                >删除</rt-button
              >
              <rt-button
                icon-name="rt-base-save"
                type="primary"
                @click="updateCampaign()"
                >保存</rt-button
              >
            </rt-header-button-group>
          </template>
        </rt-detail-header>
      </rt-header>
      <rt-content>
        <rt-card>
          <rt-section icon="rt-base-account" title="基础信息">
            <rt-form-wrapper>
              <rt-row :gutter="32">
                <rt-col :span="12">
                  <rt-form-item label="活动名称" required prop="name">
                    <rt-input
                      v-model="insertForm.name"
                      placeholder="最多支持30个字"
                    />
                  </rt-form-item>
                </rt-col>
                <rt-col :span="6">
                  <rt-form-item label="开始时间" required prop="start_time">
                    <rt-date-picker
                      v-model="insertForm.start_time"
                      placeholder="开始日期"
                      type="datetime"
                      format="yyyy-MM-dd HH:mm:ss"
                    />
                  </rt-form-item>
                </rt-col>
                <rt-col :span="6">
                  <rt-form-item required label="结束时间" prop="end_time">
                    <rt-date-picker
                      v-model="insertForm.end_time"
                      placeholder="结束日期"
                      type="datetime"
                    />
                  </rt-form-item>
                </rt-col>
              </rt-row>
              <rt-row :gutter="32">
                <rt-col :span="18">
                  <rt-row :gutter="32">
                    <rt-col :span="8"
                      ><rt-form-item label="活动地点">
                        <rt-address
                          :value="addressList"
                          placeholder="请选择省市县"
                          @input="getAdress"
                        /> </rt-form-item
                    ></rt-col>
                    <rt-col :span="14"
                      ><rt-form-item>
                        <rt-input
                          v-model="insertForm.address"
                          placeholder="请输入地址"
                        />
                      </rt-form-item>
                    </rt-col>
                  </rt-row>
                </rt-col>
                <rt-col :span="6">
                  <rt-form-item label="主讲人姓名" required prop="speaker">
                    <rt-input
                      v-model="insertForm.speaker"
                      placeholder="最多支持10个字"
                    />
                  </rt-form-item>
                </rt-col>
              </rt-row>
              <rt-row :gutter="32">
                <rt-col :span="24">
                  <rt-form-item
                    label="主讲人介绍"
                    required
                    prop="speaker_brief"
                  >
                    <rt-input
                      v-model="insertForm.speaker_brief"
                      type="textarea"
                      autosize
                      placeholder="最多支持100个字"
                    />
                  </rt-form-item>
                </rt-col>
              </rt-row>
              <rt-row :gutter="32">
                <rt-col :span="24">
                  <rt-form-item label="活动链接" prop="bbs_campaign_link">
                    <rt-input
                      v-model="insertForm.bbs_campaign_link"
                      placeholder="请输入"
                    />
                  </rt-form-item>
                </rt-col>
              </rt-row>
              <rt-row :gutter="32">
                <rt-col :span="24">
                  <rt-form-item label="备注">
                    <rt-input
                      v-model="insertForm.remark"
                      type="textarea"
                      autosize
                      placeholder="请输入"
                    />
                  </rt-form-item>
                </rt-col>
              </rt-row>
              <rt-row :gutter="32">
                <rt-col :span="6">
                  <rt-form-item>
                    <el-checkbox v-model="insertForm.is_display_start_page"
                      >在启动页展示</el-checkbox
                    >
                  </rt-form-item>
                </rt-col>
              </rt-row>
              <rt-row :gutter="32">
                <rt-col :span="12">
                  <rt-form-item label="启动页" prop="stfile">
                    <div class="file-img">
                      <el-upload
                        :on-preview="handlePictureCardPreview"
                        :on-change="stChangeFile"
                        :on-remove="removeStFile"
                        :file-list="stFileList"
                        :auto-upload="false"
                        :limit="1"
                        :show-file-list="true"
                        :on-exceed="exceedLimit"
                        accept="jpg"
                        action=""
                        list-type="picture-card"
                      >
                        <i class="el-icon-plus" />&nbsp;
                      </el-upload>
                      <el-dialog :visible.sync="dialogVisible">
                        <img :src="dialogImageUrl" width="100%" alt="" />
                      </el-dialog>
                      <div class="file-text">
                        只能上传jpg/png/jpeg文件，且不可超过2M，建议尺页750*480
                      </div>
                    </div>
                  </rt-form-item>
                </rt-col>
                <rt-col :span="12">
                  <rt-form-item label="封面图/宣传图" prop="file">
                    <div class="file-img">
                      <el-upload
                        :on-preview="handlePictureCardPreview"
                        :on-change="changeFile"
                        :on-remove="removeFile"
                        :file-list="fileList"
                        :auto-upload="false"
                        :limit="1"
                        :show-file-list="true"
                        :on-exceed="exceedLimit"
                        accept="jpg"
                        action=""
                        list-type="picture-card"
                      >
                        <i class="el-icon-plus" />&nbsp;
                      </el-upload>
                      <el-dialog :visible.sync="dialogVisible">
                        <img :src="dialogImageUrl" width="100%" alt="" />
                      </el-dialog>
                      <div class="file-text">
                        只能上传jpg/png/jpeg文件，且不可超过2M，建议尺寸750*1334
                      </div>
                    </div>
                  </rt-form-item>
                </rt-col>
              </rt-row>
            </rt-form-wrapper>
          </rt-section>
        </rt-card>
        <rt-card>
          <rt-section title="活动详情">
            <editor
              :catch-data="catchData"
              :content="insertForm.campaign_brief"
            />
          </rt-section>
        </rt-card>
      </rt-content>
    </rt-form>
  </rt-view>
</template>
<script>
import editor from '@/components/wangeditor/editor.vue';
import util from '../../libs/util';
export default {
  components: { editor: editor },
  data() {
    var campaignLink = (rule, value, callback) => {
      const val = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/;
      if (value) {
        if (val.test(value)) {
          callback();
        } else {
          callback(new Error('请输入正确的链接'));
        }
      }
      callback();
    };
    return {
      flag: '0', // 默认为0，表示不是删除的； 为1,表示是删除的;  为2表示编辑时是否有图片
      dialogImageUrl: '',
      dialogVisible: false,
      isUpdate:
        this.$route.params.id != null && this.$route.params.id != undefined,
      id:
        this.$route.params.id != null && this.$route.params.id != undefined
          ? this.$route.params.id
          : '',
      imageUrl: '',
      img: '',
      ss: false,
      insertForm: {
        name: '',
        start_time: '',
        avatar: '',
        end_time: '',
        proviceid: '',
        cityid: '',
        countyid: '',
        address: '',
        is_display_start_page: false,
        speaker: '',
        speaker_brief: '',
        bbs_campaign_link: '',
        remark: '',
        campaign_brief: ''
      },
      addressList: [],
      fileList: [], // 图片路径
      stFileList: [],
      uploadChange: false,
      errorUpload: '',
      file: null, // 封面页图片
      stfile: null, // 启动页图片
      props: { value: 'id', label: 'name' },
      rules: {
        name: [
          {
            required: true,
            message: '请输入活动名称',
            trigger: ['blur', 'change']
          },
          {
            max: 30,
            message: '最大长度为30个字符',
            trigger: ['blur', 'change']
          }
        ],
        start_time: [
          {
            required: true,
            message: '请输入活动开始时间',
            trigger: ['blur', 'change']
          }
        ],
        end_time: [
          {
            required: true,
            message: '请输入活动结束时间',
            trigger: ['blur', 'change']
          }
        ],
        speaker: [
          {
            required: true,
            message: '请输入主讲人姓名',
            trigger: ['blur', 'change']
          },
          {
            max: 10,
            message: '最大长度为10个字符',
            trigger: ['blur', 'change']
          }
        ],
        speaker_brief: [
          {
            required: true,
            message: '请输入主讲人介绍',
            trigger: ['blur', 'change']
          },
          {
            max: 100,
            message: '最大长度为100个字符',
            trigger: ['blur', 'change']
          }
        ],
        bbs_campaign_link: [
          {
            required: false,
            validator: campaignLink,
            trigger: ['blur', 'change']
          }
        ]
      },
      fromRoute: ''
    };
  },
  computed: {},
  mounted: function() {
    if (!this.isUpdate) {
      this.fileList = [];
      this.stFileList = [];
    } else {
      this.getCampaignById();
    }
  },
  methods: {
    back() {
      this.$confirm(
        '活动未保存，返回后编辑内容将不保存，是否确定返回',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          if (this.isUpdate) {
            this.$router.back();
          } else {
            this.$router.back();
          }
        })
        .catch(() => {});
    },
    releaseCampaign() {
      if (
        new Date(this.insertForm.start_time) >
        new Date(this.insertForm.end_time)
      ) {
        // rt.showErrorToast('开始时间不能大于结束时间');
        this.$message.error({
          showClose: true,
          message: '开始时间不能大于结束时间'
        });
        return;
      }
      if (
        new Date(this.insertForm.start_time) ==
        new Date(this.insertForm.end_time)
      ) {
        this.$message.error({
          showClose: true,
          message: '开始时间和结束时间不能相同'
        });
        return;
      }
      if (!this.file) {
        // rt.showErrorToast('请选择封面图片');
        this.$message.error({
          showClose: true,
          message: '请选择封面图片'
        });
        return;
      }
      if (this.insertForm.is_display_start_page && this.flag != '2') {
        // rt.showErrorToast('请选择启动页图片');
        this.$message.error({
          showClose: true,
          message: '请选择启动页图片'
        });
        return;
      }
      this.$confirm('确定发布活动么？', '保存', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$refs.insertForm.$children[0].validate(valid => {
            if (valid) {
              var formData = this.getFormDate();
              let config = {
                headers: {
                  'Content-Type': 'multipart/form-data'
                }
              };
              rt.post('api/bbs/campaign/releasecampaign', formData, config)
                .then(res => {
                  this.$router.replace({
                    name: 'campaign-detail',
                    params: { id: res }
                  });
                })
                .catch(error => {
                  // rt.showErrorToast(error);
                  this.$message.error({
                    showClose: true,
                    message: error
                  });
                });
            } else {
              return false;
            }
          });
        })
        .catch(() => {});
    },
    saveCampaign() {
      if (
        new Date(this.insertForm.start_time) >
        new Date(this.insertForm.end_time)
      ) {
        // rt.showErrorToast('开始时间不能大于结束时间');
        this.$message.error({
          showClose: true,
          message: '开始时间不能大于结束时间'
        });
        return;
      }
      // 没有存图片的话，则是null空值，逻辑判断中非空即假的操作， 存储图片的话那就是一个对象，
      // js的if判断中可以以对象作为判断条件，可以理解为对象为true
      if (!this.file) {
        // rt.showErrorToast('请选择封面图片');
        this.$message.error({
          showClose: true,
          message: '请选择封面图片'
        });
        return;
      }
      if (this.insertForm.is_display_start_page && !this.stfile) {
        // rt.showErrorToast('请选择启动页图片');
        this.$message.error({
          showClose: true,
          message: '请选择启动页图片'
        });
        return;
      }
      this.$confirm('确定保存活动么？', '保存', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$refs.insertForm.$children[0].validate(valid => {
            if (valid) {
              var formData = this.getFormDate();
              let config = {
                headers: {
                  'Content-Type': 'multipart/form-data'
                }
              };
              rt.post('api/bbs/campaign/savecampaign', formData, config)
                .then(res => {
                  this.$router.replace({
                    name: 'campaign-detail',
                    params: { id: res }
                  });
                })
                .catch(error => {
                  // rt.showErrorToast(error);
                  this.$message.error({
                    showClose: true,
                    message: error
                  });
                });
            } else {
              return false;
            }
          });
        })
        .catch(() => {});
    },
    getFormDate() {
      let formData = new FormData();
      // 此判断主要是判断是保存还是更新的操作， 更新的话是布尔类型的值true， 新建的话就是一个对象， 此判断可以理解为类型判断
      if (this.file != true) {
        // 不是更新的操作或者是更新后图片换掉的操作或者是新建保存图片的操作
        formData.append('file', this.file);
      }
      if (this.stfile != true) {
        formData.append('stfile', this.stfile);
      }
      formData.append('flag', this.flag);
      formData.append('name', this.insertForm.name);
      formData.append('avatar', this.insertForm.avatar);
      formData.append('code', this.insertForm.code);
      formData.append('proviceid', this.insertForm.proviceid);
      formData.append('cityid', this.insertForm.cityid);
      formData.append('countyid', this.insertForm.countyid);
      formData.append('address', this.insertForm.address);
      formData.append(
        'is_display_start_page',
        this.insertForm.is_display_start_page
      );
      formData.append('speaker', this.insertForm.speaker);
      formData.append('speaker_brief', this.insertForm.speaker_brief);
      formData.append('bbs_campaign_link', this.insertForm.bbs_campaign_link);
      formData.append('remark', this.insertForm.remark);
      formData.append('campaign_brief', this.insertForm.campaign_brief);
      if (this.isUpdate) {
        formData.append('bbs_campaignid', this.id);
        formData.append('start_time', new Date(this.insertForm.start_time));
        formData.append('end_time', new Date(this.insertForm.end_time));
      } else {
        formData.append('start_time', this.insertForm.start_time);
        formData.append('end_time', this.insertForm.end_time);
      }
      return formData;
    },
    removeStFile(file, fileList) {
      this.stfile = null;
      this.flag = '1';
    },
    removeFile(file, fileList) {
      this.file = null;
    },
    // 封面图片显示的操作
    changeFile(file) {
      this.uploadChange = true;
      const isJPG = file.raw.type === 'image/jpeg';
      const isPNG = file.raw.type === 'image/png';
      if (isJPG || isPNG) {
        const maxSize = 2 * 1024 * 1024;
        if (file.size > maxSize) {
          // rt.showErrorToast('上传图片最大不能大于2M');
          this.$message.error({
            showClose: true,
            message: '上传图片最大不能大于2M'
          });
          this.fileList = [];
          return false;
        } else {
          this.file = file.raw;
        }
      } else {
        // rt.showErrorToast('只能上传jpg/png/jpeg文件');
        this.$message.error({
          showClose: true,
          message: '只能上传jpg/png/jpeg文件'
        });
        this.fileList = [];
        return false;
      }
    },
    // 启动页的图片显示
    stChangeFile(file) {
      this.uploadChange = true;
      const isJPG = file.raw.type === 'image/jpeg';
      const isPNG = file.raw.type === 'image/png';
      if (isJPG || isPNG) {
        const maxSize = 1024 * 1024 * 2;
        if (file.size > maxSize) {
          // rt.showErrorToast('上传图片最大不能大于2M');
          this.$message.error({
            showClose: true,
            message: '上传图片最大不能大于2M'
          });
          this.stFileList = [];
          return false;
        } else {
          this.stfile = file.raw;
          this.flag = '2';
        }
      } else {
        // rt.showErrorToast('只能上传jpg/png/jpeg文件');
        this.$message.error({
          showClose: true,
          message: '只能上传jpg/png/jpeg文件'
        });
        this.stFileList = [];
        return false;
      }
    },
    handleRemove(file, fileList) {
      this.fileList = [];
      this.uploadChange = true;
    },
    catchData(val) {
      this.insertForm.campaign_brief = val;
    },
    getAdress(val) {
      this.insertForm.cityid = val[1];
      this.insertForm.countyid = val[2];
      this.insertForm.proviceid = val[0];
    },
    //编辑的逻辑
    getCampaignById() {
      rt.get(`api/bbs/campaign/detail/${this.id}`)
        .then(res => {
          this.insertForm = res;
          this.addressList = [res.proviceid, res.cityid, res.countyid];
          if (null != res.avatar) {
            this.fileList = [{ url: util.showRemotePic(res.avatar) }]; // 图片的路径
          }
          if (null != res.start_page) {
            this.flag = '2';
            this.stFileList = [{ url: util.showRemotePic(res.start_page) }];
          }
          this.file = true;
          this.stfile = true;
        })
        .catch(error => {
          // rt.showErrorToast(error);
          this.$message.error({
            showClose: true,
            message: error
          });
        });
    },
    updateCampaign() {
      if (
        new Date(this.insertForm.start_time) >
        new Date(this.insertForm.end_time)
      ) {
        // rt.showErrorToast('开始时间不能大于结束时间');
        this.$message.error({
          showClose: true,
          message: '开始时间不能大于结束时间'
        });
        return;
      }
      // alert(
      //   !this.file +
      //     '   ' +
      //     this.insertForm.is_display_start_page +
      //     '   ' +
      //     !this.stfile +
      //     '   ' +
      //     this.flag
      // );
      if (!this.file) {
        // rt.showErrorToast('请选择封面图片');
        this.$message.error({
          showClose: true,
          message: '请选择封面图片'
        });
        return;
      }
      if (this.insertForm.is_display_start_page && this.flag != '2') {
        // rt.showErrorToast('请选择启动页图片');
        this.$message.error({
          showClose: true,
          message: '请选择启动页图片'
        });
        return;
      }
      this.$confirm('确定保存活动么？', '保存', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$refs.insertForm.$children[0].validate(valid => {
            if (valid) {
              var formData = this.getFormDate();
              let config = {
                headers: {
                  'Content-Type': 'multipart/form-data'
                }
              };
              rt.post('api/bbs/campaign/updatecampaign', formData, config)
                .then(res => {
                  this.$router.replace({
                    name: 'campaign-detail',
                    params: { id: this.id }
                  });
                })
                .catch(error => {
                  // rt.showErrorToast(error);
                  this.$message.error({
                    showClose: true,
                    message: error
                  });
                });
            } else {
              return false;
            }
          });
        })
        .catch(() => {});
    },
    deleteCampaign() {
      rt.post(`api/bbs/campaign/singledelete/${this.id}`)
        .then(res => {
          // rt.showSuccessToast('成功');
          this.$message({
            showClose: true,
            message: '成功',
            type: 'success'
          });
          this.$router.push({
            name: 'campaign-list'
          });
        })
        .catch(error => {
          // rt.showErrorToast(error);
          this.$message.error({
            showClose: true,
            message: error
          });
        });
    },
    activateRelease() {
      rt.post(`api/bbs/campaign/activaterelease/${this.id}`)
        .then(res => {
          // rt.showSuccessToast('成功');
          this.$message({
            showClose: true,
            message: '成功',
            type: 'success'
          });
          this.getCampaignById();
        })
        .catch(error => {
          // rt.showErrorToast(error);
          this.$message.error({
            showClose: true,
            message: error
          });
        });
    },
    deactivateRelease() {
      rt.post(`api/bbs/campaign/deactivaterelease/${this.id}`)
        .then(res => {
          // rt.showSuccessToast('成功');
          this.$message({
            showClose: true,
            message: '成功',
            type: 'success'
          });
          this.getCampaignById();
        })
        .catch(error => {
          // rt.showErrorToast(error);
          this.$message.error({
            showClose: true,
            message: error
          });
        });
    },
    test() {
      this.ss = true;
    },
    handleRemove1(file, fileList) {},
    // 当前图片放大预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    exceedLimit(file, fileList) {
      if (fileList.length === 1) {
        // 解决bug4642
        this.$message.error({
          showClose: true,
          message: '图片已存在，请删除后再重新上传'
        });
        // rt.showErrorToast('封面已存在，请删除后再重新上传 ');
      }
    }
  }
};
</script>
<style>
.file-img {
  padding-top: 5px;
}
.file-text {
  padding-top: 10px;
  color: #8c939d;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
